package linkedlist;

/**
 * @author justnow
 * Created on 2020-09-30
 * Description
 * 给定一个无序单链表，实现单链表的选择排序（升序排列）
 */
public class Other1_SelectSort {
    public static ListNode sort (ListNode head) {
        // write code here
        if (head == null) {
            return head;
        }
        ListNode dumpyhead = new ListNode(head.val);
        dumpyhead.next = head;
        ListNode newDumpy = new ListNode(-1);
        ListNode newCurrent = newDumpy;
        while (dumpyhead != null) {
            int minValue = dumpyhead.val;
            ListNode current = dumpyhead.next;
            ListNode tempPre = dumpyhead;
            ListNode tempCurrent = current;
            while (current != null) {
                if (minValue > current.val) {
                    minValue = current.val;
                }
                current = current.next;
            }

            while (tempCurrent != null) {
                if (tempCurrent.val == minValue) {
                    tempPre.next = tempCurrent.next;
                    break;
                }
                tempPre = tempPre.next;
                tempCurrent = tempCurrent.next;
            }
            newCurrent.next = new ListNode(minValue);
            newCurrent = newCurrent.next;
            dumpyhead = dumpyhead.next;
        }
        return newDumpy.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(3);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        sort(head);
    }
}
